package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.ArticleRepository;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IPublishService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
public class PublishServiceImpl implements IPublishService {

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private ArticleRepository articleRepository;

    /**
     * 生成静态页面
     * @param apArticle
     * @param content
     */
    @Async
    @Override
    public void createHtml(ApArticle apArticle, String content) {
        System.out.println(Thread.currentThread().getName() + "开始执行静态页面服务");
        //使用freemarker生成html文件
        try {
            //获取模板
            Template template = configuration.getTemplate("article.ftl");
            //准备数据
            Map<String ,Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            //合并模板和数据
            Writer writer = new StringWriter();
            template.process(map,writer);

            //将文件存放到minio中
            String name = apArticle.getId()+".html";
            //构建输入流
            InputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOService.upload(name, is, "text/html");

            //将minio返回的地址保存到文章表中
            apArticle.setStaticUrl(url);
            articleService.updateById(apArticle);

            //将数据同步到es中
            ApArticleSearch articleSearch = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle,articleSearch);
            articleRepository.save(articleSearch);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
